package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.cache.util.RedisKeys;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.excption.LogicExcption;
import cn.wolfcode.wolf2w.redis.service.IUserInfRedisService;
import cn.wolfcode.wolf2w.util.Consts;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfRedisService {


    @Autowired
    private StringRedisTemplate template;

    @Override
    public String getVerifyCode(String phone) {
        String code = template.opsForValue().get(RedisKeys.VERIFY_CODE.join(phone));
        return code;
    }

    @Override
    public void setVerifyCode(String phone, String code) {
        template.opsForValue().set(RedisKeys.VERIFY_CODE.join(phone), code,
                RedisKeys.VERIFY_CODE.getTime(), TimeUnit.SECONDS);
    }

    @Override
    public String setToken(String user) {
        String token = UUID.randomUUID().toString().replace("-", "");
        template.opsForValue().set(RedisKeys.TOKEN.join(token), user, RedisKeys.TOKEN.getTime(), TimeUnit.SECONDS);
        return token;
    }

    //定义次数对象
    int count = 0;

    @Override
    public void setCount() {
        //判断是否需要限制请求
        if (template.getExpire("ex") != -2L) {
            throw new LogicExcption("系统繁忙,请稍后重试");
        }
        // 第一次请求给redis设置一个计时器计时1分钟
        if (count == 0) {
            template.opsForValue().set("time", "time", 60L, TimeUnit.SECONDS);
        }
        System.out.println(template.getExpire("time"));
        // 判断1分钟内请求次数是否超过3次
        if (count >= 3 && template.getExpire("time") != -2L) {
            // 超过三次次数清零并抛出异常
            count = 0;
            // 将异常记录在redis中并设置失效时间
            template.opsForValue().set("ex", "ex", 30L, TimeUnit.SECONDS);
            throw new LogicExcption("系统繁忙,请稍后重试");
        }
        //次数不超过3次则次数自增1
        count++;
    }

    @Override
    public UserInfo getUserByToken(String token) {
        if (token == null) {
            return null;
        }
        String key = RedisKeys.TOKEN.join(token);
        if (StringUtils.hasLength(key)){
            String userstr = template.opsForValue().get(key);
            UserInfo userInfo = JSON.parseObject(userstr, UserInfo.class);
            System.out.println("------------------------");
            if (userInfo != null) {
                template.expire(RedisKeys.TOKEN.join(token), Consts.USER_INFO_TOKEN_VAI_TIME * 60L, TimeUnit.SECONDS);
            }
            return userInfo;
        }
        return null;
    }
}
